package instance

import (
	"cloud_android_backend/api/common"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang/glog"
	rb "modules.tenxcloud.com/common/middleware"
	"modules.tenxcloud.com/common/utility/success"
	"os/exec"
	"strings"
)

type SwitchLocalKeyboardParam struct {
	Udid string `json:"udid"`
	Type string `json:"type"`
}

func SwitchLocalKeyboard(c *gin.Context) {
	//li, exists := c.Get(authorization.LoginUserKey)
	//if !exists {
	//	c.AbortWithStatusJSON(common.ErrorResponse("get user from content failed"))
	//	return
	//}
	//current := li.(*model.User)
	body, _ := c.Get(rb.RequestBodyKey)
	param := SwitchLocalKeyboardParam{}
	if err := json.Unmarshal(body.([]byte), &param); err != nil {
		glog.Error(err)
		c.AbortWithStatusJSON(common.ErrorResponse(err.Error()))
		return
	}
	if param.Udid == "" || param.Type == "" {
		c.AbortWithStatusJSON(common.ErrorResponse("udid or type is empty"))
		return
	}
	//InstanceUses := resources.InstanceUses{}
	//db, err := composite.Database.GetOrm()
	//if err != nil {
	//	glog.Error(err)
	//	c.AbortWithStatusJSON(common.ErrorResponse(err.Error()))
	//	return
	//}
	str_split := strings.Split(param.Udid, ":")
	if len(str_split) != 2 {
		c.AbortWithStatusJSON(common.ErrorResponse("udid is error"))
		return
	}
	//instance, err := InstanceUses.GetInstanceInfoByUdid(db, str_split[1], str_split[0])
	//if err != nil {
	//	glog.Error(err)
	//	c.AbortWithStatusJSON(common.ErrorResponse(err.Error()))
	//	return
	//}
	//if instance.UserId != current.UserID {
	//	glog.Error(err)
	//	c.AbortWithStatusJSON(common.ErrorResponse("Permission denied"))
	//}
	adbIme := "com.android.adbkeyboard/.AdbIME"
	adbImePkg := "com.android.adbkeyboard"
	//dbImeApkPath := "/root/ADBKeyboard.apk"
	gboardIme := "com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME"
	enableIme := adbImePkg
	if param.Type == "phone" {
		enableIme = gboardIme
	} else {
		enableIme = adbIme
	}
	go func() {
		adbImeApkPath := "/root/ADBKeyboard.apk"
		// 2. 检查 adbIme 是否安装
		out, err := runA(exec.Command("adb", "-s", param.Udid, "shell", "pm", "list", "packages"))
		if err != nil {
			fmt.Println("获取当前输入法失败: %v, 输出: %s", err, out)
		}
		if !strings.Contains(out, adbImePkg) {
			fmt.Println("ADB 输入法未安装，正在安装...")
			out2, err2 := runA(exec.Command("adb", "-s", param.Udid, "install", "-r", adbImeApkPath))
			if err2 != nil {
				fmt.Println("安装 ADB 输入法失败: %v, 输出: %s", err2, out2)
			}
			// 3. 启用 ADB 输入法

		}
	}()
	out, err := runA(exec.Command("adb", "-s", param.Udid, "shell", "ime", "enable", adbIme))
	if err != nil {
		glog.Errorf("runA error: %v;output:%s", err, out)
	}
	fmt.Println("已启用 ADB 输入法:" + out)
	// 4. 切换到 ADB 输入法
	out, err = runA(exec.Command("adb", "-s", param.Udid, "shell", "ime", "set", enableIme))
	if err != nil {

		glog.Errorf("runA error: %v;output:%s", err, out)
	}
	c.JSON(success.OK(common.SuccessResponse("上传成功")))

}
func runA(cmd *exec.Cmd) (string, error) {
	out, err := cmd.CombinedOutput()
	return string(out), err
}
